-- MachinePlatformM
-- Created by cheny3 Jun/03/2016
-- 作战平台模块

module("MachinePlatformM", package.seeall);

-- 关闭平台
function doEvent(pos)
    local grid = DungeonM.getGridByPos(pos);

    -- 如果不是平台
    if grid.type ~= GRID_TYPE_MACHINE_PLATFORM or
        grid.state == GRID_STATE_DISABLE then
        trace("MachinePlatformM", "不是作战平台或已失效。");
        return false;
    end

    -- 扣除
    local args = DungeonM.queryElement(grid.element, "args");
    local cost = args["cost"];
    if type(cost) == "table" then
        if cost[1] == 1 then
            -- 物品
            if not ItemM.costAmount(ME.user, cost[2], cost[3]) then
                -- 扣除失败
                return false;
            end
        elseif cost[1] == 2 then
            -- 属性
            if ME.user.dbase:query(cost[2], 0) < cost[3] then
                -- 不够扣除
                return false;
            end
            ME.user:costAttrib(cost[2], cost[3]);
        end
    end

    -- 改变状态
    grid:changeState(GRID_STATE_DISABLE);

    -- 抛出事件
    EventMgr.fire(event.CLOSE_MACHINE_PLATFORM, {["pos"] = grid:getPos()});

    -- 抛出一个回合事件
    EventMgr.fire(event.COMBAT_ROUND, pos);

    -- 玩家出手
    EventMgr.fire(event.PLAYER_MOVE, pos);

    return true;
end

-- 判断消耗是否足够
function enoughForCost(pos)
    local grid = DungeonM.getGridByPos(pos);

    -- 如果不是平台
    if  grid.type ~= GRID_TYPE_MACHINE_PLATFORM or
        grid.state == GRID_STATE_DISABLE then
        trace("MachinePlatformM", "不是作战平台或已失效。");
        return false;
    end

    -- 判断扣除
    local args = DungeonM.queryElement(grid.element, "args");
    local cost = args["cost"];
    if type(cost) == "table" then
        if cost[1] == 1 then
            -- 物品
            if ItemM.getAmount(ME.user, cost[2]) < cost[3] then
                -- 不够扣除
                return false;
            end
        elseif cost[1] == 2 then
            -- 属性
            if ME.user.dbase:query(cost[2], 0) < cost[3] then
                -- 不够扣除
                return false;
            end
        end
    end

    return true;
end

-- 抽取技能
function fetchSkillId(args)
    local info = ME.user.dbase:query("machine_platform") or {};

    local skills = args["buff_skill"];
    local skillId;
    if type(skills) == "number" then
        skillId = skills;
    elseif type(skills) == "table" then
        -- 先去除掉上次抽取的
        local index = table.indexOf(skills, tonumber(info["last_skill"]));
        if index >= 0 then
            table.remove(skills, index);
        end

        local seed = DungeonM.getRandSeed("machine_platform_skill");
        local index = seed % #skills + 1;   --  客户端下标比服务器多1
        skillId = skills[index];
    end

    if type(skillId) == "number" then
        args["buff_skill"] = skillId;
    else
        args["buff_skill"] = nil;
    end

    -- 记录一下
    info["last_skill"] = skillId;
    ME.user.dbase:set("machine_platform", info);

    return args;
end
